﻿using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using WeatherHistory.Data.Repositories.Interfaces;
using WeatherHistory.Shared.Exceptions;

namespace WeatherHistory.Api.CommandsQueries.Queries.Weathers.GetLast;

public class GetLastWeathersQueryHandler : IRequestHandler<GetLastWeathersQueryRequest, GetLastWeathersQueryResponse>
{
    private readonly IMapper _mapper;
    private readonly IRegionRepository _regionRepository;

    public GetLastWeathersQueryHandler(IMapper mapper, IRegionRepository regionRepository)
    {
        _mapper = mapper;
        _regionRepository = regionRepository;
    }

    public async Task<GetLastWeathersQueryResponse> Handle(GetLastWeathersQueryRequest request, CancellationToken cancellationToken)
    {
        var region = await _regionRepository
            .AsQueryable()
            .Include(x => x.WeatherRegionRelations).ThenInclude(x => x.Weather).ThenInclude(x => x.Forecasts)
            .FirstOrDefaultAsync(x => x.Id == request.RegionId, cancellationToken);

        if (region == null) throw new NotFoundException($"Регион с id'{request.RegionId}' не найден");
        if (region.WeatherRegionRelations.Count == 0) throw new NotFoundException($"Для региона '{request.RegionId}' нет записей погоды");

        var lastCreatedWeather = region.WeatherRegionRelations.MaxBy(x => x.CreatedAt)?.Weather;

        var response = _mapper.Map<GetLastWeathersQueryResponse>(lastCreatedWeather);
        response.RegionName = region.Name;
        response.Id = region.Id;

        return response;
    }
}